<?php
namespace Nawa\MedicalStudy\MedicalCenter\Monitoring;
/**
 * Medical Center Monitoring Survey.
 *
 * It represant a monotoring survey, a checklist that must be fill
 * during a monitoring
 *
 * @author Xavier VILAIN
 * @package Nawa\MedicalStudy\MedicalCenter\Monitoring
 * @license #license-nawa-survey#
 *
 * @property int	$msid				Id of the medical study
 * @property int	$mcid				Medical Center
 * @property int	$monitoringid		Monitoring Id (autoincremental)
 * @property int	$surveyid 			Id of the survey template
 * @property int	$uname				Last Author
 * @property date	$udate				Last Update Date
 * @property float	$progress			% of progress
 * 
 */
class Survey extends \Fox\Object {
		
	/**
	 * Link to the survey object
	 * @var string
	 */
	const LINK_MONITORING = 'monitoring';
	
	/**
	 * Link to Sections
	 * @var string
	 */
	const LINK_SECTIONS = 'sections';
		
	/**
	 * Link to the survey questions object
	 * @var string
	 */
	const LINK_QUESTIONS = 'questions';
	
	/**
	 * Orignal Survey Template
	 * @var \Nawa\Survey
	 */
	private $_template = null;

	/**
	 * Render the Survey as an HTML form
	 * @return string
	 */
	public function template() {
		if(empty($this->_template)) {
			/* @var $surveyTemplate \Nawa\Survey */
			$this->_template = \Fox\Dao::load(\Nawa\Survey::className(),$this->surveyid);
			if($this->monitoring()->isValitated()) {
				/*
				$versions = $this->_template->versions();
				
				$this->_template->switchToVersion($versions[$this->version - 1]);
				*/
			} else {
				
			}
		}
		return $this->_template;
	}
		
	/**
	 * Render the Survey as an HTML form
	 * @return string
	 */
	public function render($initialize = null) {
		// Build Tree
		$output =  $this->template()->render($initialize);
		return $output;
	}
	
	/**
	 * (non-PHPdoc)
	 * @see Fox.Object::delete()
	 */
	public function delete() {
		// Remove Surveys
		foreach($this->sections() as $section) {
			$section->delete();
		}
		// Remove Surveys
		foreach($this->questions() as $question) {
			$question->delete();
		}
		parent::delete();
	}
}
\Fox\Dao::infos(Survey::className(),
new \Fox\Object\Info('ms_mc_monitoring_surveys', \Fox\Databases::DB_APP)
);

// Link To Sections
\Fox\Object\Links::add(\Fox\Dao::link(Survey\Section::className(),Survey\Section::LINK_SURVEY)
	->to(Survey::className(), Survey::LINK_SECTIONS)
	->on('msid','mcid','monitoringid','surveyid')
	->versionFrom()
);
// Link To Questions
\Fox\Object\Links::add(\Fox\Dao::link(Survey\Question::className(),Survey\Question::LINK_SURVEY)
	->to(Survey::className(), Survey::LINK_QUESTIONS)
	->on('msid','mcid','monitoringid','surveyid')
);